/*
 *  Copyright 2008 Danny Lagrouw
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */
package org.bastion.example.domain;

import java.util.ArrayList;
import java.util.List;

import org.bastion.domain.Domain;
import org.bastion.domain.ExampleDomainObject;
import org.bastion.domain.Alert.Level;
import org.bastion.message.AlertMessage;
import org.bastion.message.QueryMessage;
import org.bastion.query.DomainQuery;
import org.bastion.query.Matcher;

/**
 * @author Danny Lagrouw
 *
 */
public class Client extends ExampleDomainObject {

	private static final long serialVersionUID = 1L;

	private String name;
	
	private List<Reservation> reservations = new ArrayList<Reservation>();
	
	private List<Rental> rentals = new ArrayList<Rental>();

	private Client() {
		super(false);
	}
	
	public Client(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	protected void addReservation(Reservation reservation) {
		reservations.add(reservation);
	}

	protected void addRental(Rental rental) {
		rentals.add(rental);
	}

	@Override
	public String toString() {
		return super.toString() + "/name=" + name;
	}

	public List<Reservation> getReservations() {
		return reservations;
	}
	
	protected static boolean foundWithName(final String name) {
		DomainQuery<Client> query = new DomainQuery<Client>(Client.class);
		query.setName("ClientByName");
		query.setParameter("name", name);
		query.setMatcher(new Matcher<Client>() {
			@Override
			public boolean match(Client client) {
				return client.getName().equals(name);
			}});
		QueryMessage<Client> message = Domain.notify(new QueryMessage<Client>(query));
		return message.getSingleResult() != null;
	}
	
	public static Client create(String name) {
		if (foundWithName(name)) {
			Domain.notify(new AlertMessage("Name exists", Level.ERROR));
			return null;
		} else {
			return new Client(name);
		}
	}
	
}
